#!env/bin/python
import logging
import asyncio
from aiogram import Bot, Dispatcher, executor, types, utils
from os import getenv
from sys import exit
from app.data_provider import check_notifications_now

from app.event import handle_event_message

bot_token = getenv("BOT_TOKEN")
if not bot_token:
    exit("Error: no token provided")

try:
    bot = Bot(token=bot_token, parse_mode=types.message.ParseMode.MARKDOWN_V2)
except utils.exceptions.ValidationError:
    exit("Произошла ошибка валидации токена. Возможно, вам нужно указать \
    правильный бот токен в переменных окружения.\n=== Завершение программы ===")

dp = Dispatcher(bot)
logging.basicConfig(level=logging.INFO)


async def check_time_and_send_message(sleep_for):
    while True:
        await asyncio.sleep(sleep_for)
        notifications = check_notifications_now()
        for n in notifications:
            await bot.send_message(n["chat_id"], n["message"])


@dp.message_handler(commands=["start", "help"])
async def cmd_test1(message: types.Message):
    await message.reply("*Здесь* будет небольшая инструкция\nпо пользованию\!")


@dp.message_handler(lambda message: message.text.lower().startswith('встреча+'))
async def event(message: types.Message):
    try:
        message_now = handle_event_message(message)
    except ValueError as error:
        await message.answer("Ошибка ввода данных: " + error.args[0])
    else:
        await message.answer(message_now)
    finally:
        await message.delete()


@dp.message_handler()
async def any_text_message(message: types.Message):
    pass
    #await message.answer(message.text)
    #await message.answer(message.md_text)
    #await message.answer(message.html_text)

if __name__ == "__main__":
    print(f"Bot has been started...")
    loop = asyncio.get_event_loop()
    loop.create_task(check_time_and_send_message(60))
    executor.start_polling(dp, skip_updates=True)
